package com.zhuky.rabbit.service;

import com.alibaba.fastjson.JSON;
import com.zhuky.rabbit.constant.Constants;
import com.zhuky.rabbit.mapper.MessageLogMapper;
import com.zhuky.rabbit.mapper.OrderMapper;
import com.zhuky.rabbit.model.MessageLog;
import com.zhuky.rabbit.model.Order;
import com.zhuky.rabbit.producer.RabbitOrderSender;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MessageLogMapper messageLogMapper;
    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    public void createOrder(Order order) throws Exception {
        /**
         * step 1：订单入库
         */
        Date currentTime = new Date();
        orderMapper.insert(order);
        MessageLog messageLog =new MessageLog();
        messageLog.setMessageId(order.getMessageId());
        messageLog.setMessage(JSON.toJSONString(order));
        messageLog.setStatus(Constants.ORDER_SENDING);
        messageLog.setNextRetry(DateUtils.addMinutes(currentTime, Constants.ORDER_TIMEOUT));
        messageLog.setCreateTime(currentTime);
        messageLog.setUpdateTime(currentTime);
        messageLog.setTryCount(0);
        messageLogMapper.insert(messageLog);

        /**
         * step 2：向 MQ 发送 Message
         */
        rabbitOrderSender.send(order);

    }
}
